package com.lagou.client;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class Config {
    private static Properties properties = null;

    public static String getProperty(String key) {
        if(properties == null) {
            try {
                properties = new Properties();
                String filePath = Config.class.getResource("/").getPath()+"config.properties";
                FileInputStream fileInputStream = new FileInputStream(filePath);
                properties.load(fileInputStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return properties.getProperty(key);
    }

    private static CuratorFramework client = null;

    public static CuratorFramework getCurator() {
        if(client == null) {
            String zkServers = Config.getProperty("rpc.registry.zookeeper.host");
            RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);
            client = CuratorFrameworkFactory.builder()
                    .connectString(zkServers)
                    .sessionTimeoutMs(50000)
                    .connectionTimeoutMs(30000)
                    .retryPolicy(exponentialBackoffRetry)
                    .namespace("txy_rpc")  // 设置了一个独立的命名空间 /base
                    .build();

            client.start();
            System.out.println("curator 客户端初始化完成 servers=" + zkServers);
        }
        return client;
    }

    public static void main(String[] args) {
        String property = Config.getProperty("rpc.registry.zookeeper.host");
        System.out.println(property);
    }
}

